<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/12/17 0017
 * Time: 13:27
 */

namespace app\api\controller;


use app\admin\model\User;
use app\api\controller\Money\Money;
use app\api\model\MoneyRecord;
use app\api\model\ProductOrder;
use app\api\model\ProductOrderRelation;
use app\api\model\Shop;
use app\common\model\ProductOrderSpell;
use app\common\model\ProductOut;
use app\lib\exception\FailedException;
use think\Db;

class Task{
    /**
     * 发货7天自动收货定时任务 time()-604800
     * @return \think\response\Json
     * @throws FailedException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateOrderSevenDay(){
        //查询到所有7天外的待收货订单
        $orderWhere[] = ["status","eq","2"];
        $orderWhere[] = ["send_time","lt",time() - 604800];
        $data = (new \app\api\model\ProductOrder())->where($orderWhere)->select()->toArray();
        Db::startTrans();
        foreach ($data as $k=>$v) {
            $res = (new \app\api\model\ProductOrder())->where("id", $v['id'])->update(['status' => 4, 'sure_time' => time()]);//4是已完成
            if (!$res) {
                Db::rollback();
                throw new FailedException(['msg' => '操作失败']);
            }
            //[不做硬性处理]处理订单 销量
            (new \app\api\model\ProductOrder())->addSales($v['id']);
//            $res = (new \app\api\model\ProductOrder())->addSales($v['id']);
//            if ($res['code'] != 1) {
//                Db::rollback();
//                throw new FailedException(['msg' => $res['msg']]);
//            }

            //处理用户购次和 交易额
            $res = (new \app\admin\model\User())->where([['id', 'eq', $v['user_id']]])->setInc("buy_card_number");
            $res1 = (new \app\admin\model\User())->where([['id', 'eq', $v['user_id']]])->setInc("trade_money", $v['total_price']);
            if (!$res || !$res1) {
                Db::rollback();
                throw new FailedException(['msg' => '用户交易修改失败']);
            }
            if ($v['uid'] > 0) {
                //将对应金额加入到商家的余额下面(大于零则有对应商家)
                $shopModel = (new Shop())->where("id", $v['uid'])->find();
                if($shopModel != null){
                    $res = (new Shop())->where("id", $v['uid'])->setInc("money", (double) $v['total_price']);
                    if (!$res) {
                        Db::rollback();
                        throw new FailedException(['msg' => '商家加入余额失败']);
                    }
                    //处理商家等级
                    $res = (new \app\api\model\ProductOrder())->shopLevel($v['uid'], $v['total_price']);
                    if ($res['code'] != 1) {
                        Db::rollback();
                        throw new FailedException(['msg' => $res['msg']]);
                    }
                }
            }

            //处理佣金
            (new \app\api\model\Money())->insertInviteRecord($v['id']);
        }
        Db::commit();
        return writeJson(200,[],"操作成功");
    }

    /**
     * 收货后3天自动返佣金定时任务
     * @return \think\response\Json
     * @throws FailedException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateOrderThreeDay(){
        $moneyRecordService = new MoneyRecord();
        $moneyService = new \app\api\model\Money();
        $where[] = ["money_type","eq","0"];
        $where[] = ["money_source_type","eq","0"];
        $where[] = ["pay_status","eq","0"];
        $where[] = ["create_time","<",time() - 259200];
        $list = $moneyRecordService->field("id,money_id,money")->where($where)->select()->toArray();
        foreach ($list as $k=>$v){
            Db::startTrans();
            //更改该用户钱包金额
            $moneyWhere["id"] = $v["money_id"];
            $res = $moneyService->where($moneyWhere)->setInc("money",$v["money"]);
            if (!$res) {
                Db::rollback();
                throw new FailedException(['msg' => '操作失败']);
            }
            //更改账单状态
            $v["pay_status"] = 2;
            $v["pay_time"] = time();
            //更改当前账单状态
            $res = $moneyRecordService->dataUpdate($v);
            if (!$res) {
                Db::rollback();
                throw new FailedException(['msg' => '操作失败']);
            }
            Db::commit();
        }
        return writeJson(200,[],"操作成功");
    }

    /**
     * 订单未支付自动取消
     * @return bool
     * @throws FailedException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateCancelOrder()
    {
        //过期时间(分钟)
        $configTime = 1;

        Db::startTrans();
        //查询所有满足条件的未支付的一级订单
        // select * from om_product_order_relation where delete_time is null and pay_status = 1 and create_time < 1578732081
        $where[] = ["pay_status", "eq", 1];
        $where[] = ["create_time", "<", strtotime('-' . $configTime . ' Minute')];
        $list = (new ProductOrderRelation())
            ->field("id,pay_status")
            ->where($where)
            ->select()
            ->toArray();
        $relationIdArray = array_column($list, "id");

        //将所有支付状态改为已取消
        foreach ($list as $k => $v) {
            $list[$k]["pay_status"] = -1;
        }

        //查询所有二级订单
        $productOrderService = (new ProductOrder());
        $orderList = $productOrderService->field("id,order_type,order_type_id,status,cancel_reason,total_number")
            ->where("relation_id", "in", $relationIdArray)
            ->select()
            ->toArray();

        $productOrderSpellService = new ProductOrderSpell();
        $spellOrderList = [];
        //将所有订单设置为取消状态，并进行处理
        foreach ($orderList as $k => $v) {
            $orderList[$k]["status"] = -1;
            $orderList[$k]["cancel_reason"] = "超时未支付";

            //清仓订单处理
            if ($v["order_type"] == 2) {
                array_push($spellOrderList, $v);
            }

            //拼团订单需要回退团占位，标记占位删除
            if ($v["order_type"] == 3) {
                $productOrderSpellService->falseOrderSpell($v["id"]);
            }
        }

        //更新一级订单
        $res = (new ProductOrderRelation())->saveAll($list);
        if (!$res) {
            Db::rollback();
            throw new FailedException(['msg' => '一级订单更新失败']);
        }

        //更新二级订单
        $res = $productOrderService->saveAll($orderList);
        if (!$res) {
            Db::rollback();
            throw new FailedException(['msg' => '二级订单更新失败']);
        }
        Db::commit();

        //清仓清单需要回退商品占位
        $productOutService = new ProductOut();
        foreach ($spellOrderList as $k => $v) {
            $productOutService->falseOutOrder($v["id"], $v["total_number"]);
        }

        return writeJson(200, [], "操作成功");
    }

    /**
     * 更新用户会员到期情况
     * (每天更新)
     */
    public function updateUserType(){
        $userService = new User();
        $where[] = ["vip_time","<",time()];
        $where[] = ["user_type","eq",2];

        $res = $userService->fieldUpdate("user_type",1,"",$where);
        if($res){
            return writeJson(200,[],"操作成功");
        }else{
            throw new FailedException(['msg'=>'操作失败']);
        }
    }
}